<!--  -->
<template>
  <div class="app-container">
<el-card style="height: 80px; margin-bottom: 10px;">
  <div style="margin-bottom: 20px;">
    <el-row :guest="20">
      <el-col :span="6">
        <el-input v-model="query.name" placeholder="请输入姓名或手机号" clearable @clear="getAdminList" />
      </el-col>
      <el-col :span="2">
        <el-button type="success" style="margin-left: 10px;" icon="el-icon-search" size="medium" @click="getAdminList">
          搜索
        </el-button>
      </el-col>
      <el-col :span="2">
        <el-button style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline" size="medium" @click="add">
          添加
        </el-button>
      </el-col>
    </el-row>
  </div>
</el-card>

<el-card>
    <el-table
      v-loading="listLoading"
      :data="list" 
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录名" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.telephone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" width="310px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="success" icon="el-icon-circle-plus-outline" size="mini" plain round @click="toAssignRole(row)">
            分配角色
          </el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini" plain round @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" icon="el-icon-delete" type="danger" plain round @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="totalCount>0" :total="totalCount" :page.sync="query.currPageNo" :limit.sync="query.pageSize" @pagination="getAdminList" />
 </el-card>

 <!-- START 添加操作员弹出对话框窗口 START -->
<el-dialog  :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="700px">
  <el-form ref="dataFormRef" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 600px; margin-left:40px;">
    <el-row>
      <el-col :span="10">
        <el-form-item label="登录名" prop="username">
          <el-input v-model="temp.username" placeholder="登录名" />
        </el-form-item>
      </el-col>
      <el-col :span="12" :offset="1">
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" type="password" placeholder="密码" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" placeholder="姓名" />
        </el-form-item>
      </el-col>
      <el-col :span="12" :offset="1">
        <el-form-item label="手机" prop="phone">
          <el-input v-model="temp.phone" placeholder="手机" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="temp.telephone" placeholder="电话" />
        </el-form-item>
      </el-col>
      <el-col :span="12" :offset="1">
        <el-form-item label="地址" prop="address">
          <el-input v-model="temp.address" placeholder="地址" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="头像" prop="userFace">
      <el-input v-model="temp.userFace" style="display: none" class="id" />
      <single-upload v-model="temp.userFace" />
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="temp.remark" :autosize="{ minRows: 3, maxRows: 6}" type="textarea" placeholder="请输入备注内容" />
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="cancelEvent()">
      取消
    </el-button>
    <el-button type="primary" @click="dialogStatus==='create'?insertData():updateData()">
      确认
    </el-button>
  </div>
</el-dialog>
<!-- END 添加操作员弹出对话框窗口 END -->
<!-- START 分配角色对话框窗口 START -->
<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogVisible" width="400px">
  <el-form ref="assignRoleRef" :model="assignRole" label-position="left" label-width="70px" style="width: 350px; margin-left:30px;">
    <el-form-item label="角色名">
      <el-tree
        ref="roleRef"
        class="tree-border"
        :data="roleOptions"
        show-checkbox
        node-key="id"
        empty-text="加载中，请稍候"
        :props="defaultProps"
      />
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="cancelAssign()">
      取消
    </el-button>
    <el-button type="primary" @click="confirmAssign()">
      确认
    </el-button>
  </div>
</el-dialog>
<!-- END 分配角色对话框窗口 END -->



  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
// 从src/api/user.js中解构出pageUserList()方法并在当前组件中导入
import { pageUserList,saveAdmin,findByAdminId,updateAdmin,delAdmin } from '@/api/user'
import { roleTreeselect,toAdminAssignRole,getAdminRoleList} from '@/api/role'
// 导入分页公共组件
import Pagination from '@/components/Pagination'
import singleUpload from '@/components/upload/singleUpload'
export default {
// import引入的组件需要注入到对象中才能使用
  components: {
    Pagination,
    singleUpload
  },
  data() {
    // 验证手机的自定义校验规则
    var checkPhone = (rule, value, callback) => {
      // 定义验证手机号码的正则表达式
      const regMobile = /^1\d{10}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        return callback(new Error('请输入合法的手机号码'))
      }
    }
    // 这里存放数据
    return {
      // 用来保存t_admin管理员查询出来的分页列表信息
      list: null,
      // 用来保存分页时所需要的总记录数
      totalCount: 0,
      // 当发送异步请求用户列表数据时设置它为true,可出现正在加载中
      listLoading: true,
      query: {
        // 当前页码
        currPageNo: 1,
        // 每页显示的记录数
        pageSize: 4,
        // 查询条件，此处查询是以用户名和手机号码进行模糊查询
        name: '' 
      },
      // 添加用户的表单对象
      temp: {
        id: undefined,
        name: '',
        phone: '',
        telephone: '',
        address: '',
        state: 1,
        username: '',
        password: '',
        userFace: '',
        remark: ''
      },
      dialogFormVisible:false,
      textMap: {
        update: '编辑',
        create: '添加',
        assign: '分配角色'
      },
      dialogStatus: '',
      // 添加表单验证规则对象
      rules: {
        name: [
          { required: true, message: '姓名必填', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名的长度在2~10个字符之间', trigger: 'blur' }],
        phone: [
          { required: true, message: '手机号必填', trigger: 'blur' },
          /* validator: checkPhone 来调用data(){ }中定义的手机号格式校验规则 */
          { validator: checkPhone, trigger: 'blur' }
        ],
        username: [
          { required: true, message: '登录名必填', trigger: 'blur' },
          { min: 2, max: 10, message: '登录名的长度在2~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '密码长度在3~15位之间', trigger: 'blur' }
        ]
      },
      dialogVisible:false,//控制分配角色弹框的显示和隐藏
      assignRole:{//绑定分配角色表单
          adminId:0,
          rid:[]
      },
      roleOptions:[],//可供选择的角色列表
      defaultProps:{
        label:'nameZh'//树形组件显示对象中的哪一个属性
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 调用查询管理员分页列表信息的方法
    this.getAdminList()
  }, // 如果页面有keep-alive缓存功能，这个函数会触发
  // 方法集合
  methods: {
    // 重置Temp对象
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        phone: '',
        telephone: '',
        address: '',
        state: 1,
        username: '',
        password: '',
        userFace: '',
        remark: ''
      }
    },
    // 定义查询管理员分页列表信息的方法
    getAdminList() {
      // true时，表格中就会出现正在加载图标
      this.listLoading = true
      // 调用src/api/user.js中的pageUserList()
      pageUserList(this.query).then((res) => {
        this.listLoading = false
        this.list = res.data.list
        // 获取总记录数
        this.totalCount = res.data.totalCount
      }).catch((error) => {
        console.log(error)
        this.$message({
          title: '提示',
          message: '操作员列表查询失败',
          type: 'error',
          duration: 2000
        })
      })
    },
    // 编辑按扭的点击事件
    handleUpdate(row) {
        //1.显示编辑框
        this.dialogFormVisible=true;
        //2.设置标题
        this.dialogStatus="update";
        //3.显示数据
        findByAdminId(row.id).then((res)=>{
            this.temp=res.data;
        }).catch((err)=>{
          console.log(err);
        });
    },
    // 删除按扭的点击事件
    handleDelete(row, index) {
      //1.弹出确认框
       this.$confirm('确认要删除当前操作员信息吗?', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
       }).then(()=>{
          delAdmin(row.id).then((res)=>{
              //1.给出提示
               this.$message({
                  title: '提示',
                  message: res.message,
                  type: 'success',
                  duration: 2000
              });
              //2.刷新列表
              this.getAdminList();
          }).catch((err)=>{
            console.log(err);
          })
       }).catch((err)=>{
          console.log(err);
       })

      //2.调用后台进行删除
    },
    add(){
      this.dialogFormVisible=true;
      this.dialogStatus="create";
    },
    insertData(){
        //表单验证
        //获取表单
        this.$refs['dataFormRef'].validate((valid)=>{
          if(valid){//验证成功
             saveAdmin(this.temp)
              .then((res)=>{
                if(res.code==200){
                    //1.给出提示
                    this.$message({
                      title: '提示',
                      message: res.message,
                      type: 'success',
                      duration: 2000
                    });
                    //2.刷新列表数据
                    this.getAdminList();
                    //3.关闭新增弹框
                    this.dialogFormVisible=false;
                    //4.清空数据
                    this.resetTemp();
                }else{
                    this.$message({
                      title: '提示',
                      message: res.message,
                      type: 'error',
                      duration: 2000
                    })
                }
              })
              .catch((err)=>{
                console.log(err);
              });

          }
        })
    },
    updateData(){
        //表单验证
        //获取表单
        this.$refs['dataFormRef'].validate((valid)=>{
          if(valid){//验证成功
             updateAdmin(this.temp)
              .then((res)=>{
                if(res.code==200){
                    //1.给出提示
                    this.$message({
                      title: '提示',
                      message: res.message,
                      type: 'success',
                      duration: 2000
                    });
                    //2.刷新列表数据
                    this.getAdminList();
                    //3.关闭新增弹框
                    this.dialogFormVisible=false;
                    //4.清空数据
                    this.resetTemp();
                }else{
                    this.$message({
                      title: '提示',
                      message: res.message,
                      type: 'error',
                      duration: 2000
                    })
                }
              })
              .catch((err)=>{
                console.log(err);
              });
          }
        })
    },
    //分配角色
    toAssignRole(row){
        //1.弹框
        this.dialogVisible=true;
        //2.设置标题
         this.dialogStatus="assign";
         //3.发送异步请求查询可供选择角色
         roleTreeselect().then((res)=>{
            this.roleOptions=res.data;
         }).catch((err)=>{
           console.log(err);
         })
         //4.给分配角色数据模型adminid赋值
         this.assignRole.adminId=row.id;
         //5.查询出该用户已分配角色
         getAdminRoleList(row.id).then((res)=>{
            //设置树形组件选中的节点
            this.$refs['roleRef'].setCheckedKeys(res.data.rid);
         }).catch((err)=>{
           console.log(err);
         })
    },
    //保存分配的角色
    confirmAssign(){
        //获取树形组件
        let checkKeys=this.$refs['roleRef'].getCheckedKeys();
        // console.log(checkKeys);
        if(checkKeys.length>0){
          this.assignRole.rid=checkKeys;
          toAdminAssignRole(this.assignRole).then((res)=>{
            if(res.code==200){
                //1.给出提示
                this.$message({
                  title: '提示',
                  message: res.message,
                  type: 'success',
                  duration: 2000
                });
                //2.刷新列表数据
                this.getAdminList();
                //3.关闭新增弹框
                this.dialogVisible=false;
            }else{
              this.$message({
                  title: '提示',
                  message: res.message,
                  type: 'error',
                  duration: 2000
              })
            }
          }).catch((err)=>{
            console.log(err)
          })
         }else{
            this.$message({
              title: '提示',
              message: "请选择要分配的角色",
              type: 'info',
              duration: 2000
            })
         }
    }
  }
}
</script>
<style scoped>

</style>
